#pragma once

#include <iostream>
#include <string>
#include "InetAddr.hpp"
#include <set>
#include"Log.hpp"

using namespace LogModule;

class Command
{
public:
    Command()
    {
        _whiteListCommand.insert("ls");
        _whiteListCommand.insert("pwd");
        _whiteListCommand.insert("ls -l");
        _whiteListCommand.insert("ls -a -l");
        _whiteListCommand.insert("whoami");
        _whiteListCommand.insert("touch");
        _whiteListCommand.insert("cat");
    }

    bool IsSafeCommand(const std::string &cmd)
    {
        auto iter = _whiteListCommand.find(cmd);
        return iter != _whiteListCommand.end();
    }

    std::string Excute(const std::string &cmd, InetAddr &addr)
    {
        //1.属于白名单
        if(!IsSafeCommand(cmd))
        {
            return std::string("无权限执行该命令");
        }

        //2.执行命令
        std::string who = addr.StringAddr();
        //popen在网络通信中主要执行系统命令并获取其输出
        FILE* fp = popen(cmd.c_str(),"r");
        if(fp==nullptr)
        {
            return std::string("你要执行的命令不存在");
        }

        std::string res;
        char line[1024];
        //执行结果从fp中读
        while(fgets(line,sizeof(line),fp))
        {
            res+=line;
        }

        pclose(fp);
        std::string result = who+"excute done,result is:\n" + res;
        LOG(LogLevel::DEBUG)<<result;
        return result;
    }

    ~Command()
    {
    }

private:
    std::set<std::string> _whiteListCommand;
};